package com.zzyl.framework.interceptor;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Waker
 * @description:
 * @create 2025-09-13-20:43
 */
@Component
public class MemberInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;

    /**
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.从请求头中获取token
        String token = request.getHeader("authorization");
        // 2.判断token是否为空，如果为空则直接返回401
        if (StrUtil.isBlank(token)) {
            responseTokenParseFailed(response, "token为空，验证失败！");
        }
        // 3.解析token,如果解析失败则返回401
        Claims claims = null;
        try {
            claims = tokenService.parseToken(token);
        } catch (Exception e) {
            responseTokenParseFailed(response, "token异常，解析失败！");
        }
        // 4.从token中获取用户id,如果为用户id空则返回401
        Long userId = MapUtil.getLong(claims, "userId");
        if (ObjectUtil.isEmpty(userId)) {
            responseTokenParseFailed(response, "用户id为空，验证失败！");
        }
        // 5.将用户id保存到ThreadLocal中
        UserThreadLocal.set(userId);
        // 6.返回true 放行
        return true;
    }

    private static void responseTokenParseFailed(HttpServletResponse response, String message) {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        throw new BaseException(message);
    }

    /**
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
